package cn.yunhe.view;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.document.AbstractXlsView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * Created by zs on 2017/12/19.
 */
public class ExcelView extends AbstractXlsView {
    //文件名
    private String fileName = null;

    //导出视图自定义接口
    private ExcelExportService excelExportService = null;

    public ExcelView(ExcelExportService excelExportService) {
        this.excelExportService = excelExportService;
    }

    protected void buildExcelDocument(Map<String, Object> model, Workbook workbook, HttpServletRequest request, HttpServletResponse response) throws Exception {
        //如果没有实现接口
        if (excelExportService == null) {
            throw new RuntimeException("导出服务的接口不能为null");
        }

        //文件名不为空
        if (!StringUtils.isEmpty(fileName)) {
            //转码
            String reqCharset = request.getCharacterEncoding();
            reqCharset = reqCharset == null ? "UTF-8" : reqCharset;
            fileName = new String(fileName.getBytes(reqCharset), "ISO8859-1");
            //设置文件头
            response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        }

        //回调接口的实现
        excelExportService.markWorkBook(model, workbook);
    }


    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public ExcelExportService getExcelExportService() {
        return excelExportService;
    }

    public void setExcelExportService(ExcelExportService excelExportService) {
        this.excelExportService = excelExportService;
    }
}
